
import React, { lazy, Suspense } from 'react'
import { createHashRouter, Navigate } from "react-router-dom";
import { routerConfig, routerConfigType } from './config'
import lazyLoad from './util/lazyLoad'

function renderRouter(router: routerConfigType): any {
  console.log(router)
  // 判断是否需要重定向
  if (router.redirect) return {
    path: router.path,
    element: <Navigate to={router.redirect} />
  }
  const pages = import.meta.glob(['@/pages/**/*.tsx', '@/layout/**/*.tsx', '!@/pages/**/components/*', '!@/layout/**/components/*'])
  const r:any = {
    path: router.path
  }
  if (router.component) {
    const filePath = "/src" + router.component + '.tsx'
    if (!pages[filePath]) new Error("无效路径" + router.component)
    r.element = lazyLoad(lazy(pages[filePath] as any))
      // 是否是父节点
   if (router.routes && router.routes.length) {
    return {
      ...r,
      children: router.routes.map(renderRouter)
    }
   } else {
    return r
   }
  } else {
    if (router.routes && router.routes.length) {
      return {
        ...r,
        children: router.routes.map(renderRouter)
      }
     } else {
      new Error("无效路径" + router.component)
     }
  }
}

export const globalRouters = createHashRouter(routerConfig.map(renderRouter))